package com.boolib.http.core.abstracts;

import com.boolib.http.core.face.handler.Handler;
import com.boolib.http.core.face.handler.RequestHandler;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.util.Objects;

/**
 * @author wfq
 */
@Slf4j
public abstract class AbstractRequestHandler  implements RequestHandler {


    @Override
    public boolean isRequest() {
        return  this.isRequest;
    }



    protected HttpServletRequest httpServletRequest;

    protected HttpServletResponse httpServletResponse;

    private RequestHandler next ;

    private boolean isRequest = false;



    @Override
    public RequestHandler next() {
        return this.next;
    }


    @Override
    public void setNextRequestHandler(RequestHandler requestHandler) {
        this.next = requestHandler;
    }


    @Override
    public void handler(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {


        log.debug("AbstractRequestHandler:默认处理");
    }

    @Override
    public void requestHandler(HttpServletRequest httpServletRequest) {

    }

    @Override
    public void responseHandler(HttpServletRequest httpServletRequest) {

    }

    @Override
    public void fireHandler( HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

         this.httpServletRequest = httpServletRequest;
         this.httpServletResponse = httpServletResponse;

        if(this.isSupport()){
            this.handler( httpServletRequest,httpServletResponse);
        }

        RequestHandler next = this.next();

        if(Objects.nonNull(next)){
              //如果handler里进行了处理那么就需要传递到下一个
              next.fireHandler(this.httpServletRequest,this.httpServletResponse);
        }

        return ;

    }

    /***
     * 判断是否变化为包装类型
     * @return
     */
    @Override
    public boolean isWrapper() {
        return (this.httpServletRequest instanceof HttpServletRequestWrapper) || (this.httpServletResponse instanceof HttpServletResponseWrapper);
    }

    @Override
    public HttpServletRequest getHttpServletRequestWrapper() {
        return this.httpServletRequest;
    }

    @Override
    public HttpServletResponse getHttpServletResponseWrapper() {
        return this.httpServletResponse;
    }
}
